import Vue from 'vue'
import { login, logout, phoneLogin } from "@/api/login"
import {
  ACCESS_TOKEN,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  USER_AUTH,
  USER_INFO,
  USER_NAME
} from "@/store/mutation-types"
import { welcome } from "@/utils/util"
import { queryPermissionsByUser } from '@/api/api'

const user = {
  state: {
    token: '',
    username: '',
    realName: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realName, welcome }) => {
      state.username = username
      state.realName = realName
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    RESET_STATE: (state) => {
      Object.assign(state, () => user.state)
    },
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          // let response = { code: 200, result: { username: 'admin', token: 123456, sysAllDictItems: [], userInfo: { username: 'admin', realName: '管理员', avatar: '' } } }
          if (response.code === 200) {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 12 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 12 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 12 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 12 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username, realName: userInfo.realName, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    //手机号登录
    PhoneLogin ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo).then(response => {
          if (response.code === 200) {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 12 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 12 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 12 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 12 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username, realName: userInfo.realName, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetPermissionList ({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser().then(response => {
        //   let response = {
        //     result: {
        //       menu: [
        //         { id: '1', name: '问卷管理', url: 'questionnaire/list', hidden: false },
        //         { id: '2', name: '问卷编辑', url: 'questionnaire/form-modal', hidden: true },
        //         { id: '3', name: '基本信息', url: 'questionnaire/basic', hidden: true },
        //         { id: '4', name: '问卷明细', url: 'questionnaire/details', hidden: true },
        //         { id: '5', name: '问卷分析', url: 'questionnaire/analyse', hidden: true },
        //         { id: '6', name: '系统管理', hidden: false, children: [
        //             { id: '7', name: '用户管理', url: 'sys/user', hidden: false },
        //             { id: '8', name: '角色管理', url: 'sys/role', hidden: false },
        //             { id: '9', name: '部门管理', url: 'sys/dept', hidden: false },
        //             { id: '10', name: '菜单管理', url: 'sys/menu', hidden: false },
        //           ]
        //         },
        //       ],
        //       auth: [
        //         'sys:user:list',
        //         'sys:dept:list',
        //         'sys:role:list',
        //       ],
        //     }
        //   }

          const menuData = [ ...[{ id: '0', name: '首页', url: 'home', hidden: 1 }], ...response.result.menu];
          const authData = response.result.auth;
          const allAuthData = response.result.allAuth;

          // 保存浏览器会话存储
          sessionStorage.setItem(USER_AUTH, JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData));

          // 判断子菜单全部隐藏，将隐藏父菜单
          // if (menuData && menuData.length > 0) {
          //   menuData.forEach((item, index) => {
          //     if (item["children"]) {
          //       let hasChildrenMenu = item["children"].filter((i) => {
          //         return !i.hidden || i.hidden === false
          //       })
          //       if (hasChildrenMenu == null || hasChildrenMenu.length === 0) {
          //         item["hidden"] = true
          //       }
          //     }
          //   })
          //   commit('SET_PERMISSIONLIST', menuData)
          // } else {
          //   reject('getPermissionList: permissions must be a non-null array !')
          // }
          commit('SET_PERMISSIONLIST', menuData)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token;
        commit('RESET_STATE') // must remove  token  first
        // Vue.ls.remove(ACCESS_TOKEN)
        // Vue.ls.remove(USER_NAME)
        Vue.ls.remove(ACCESS_TOKEN)
        //console.log('logoutToken: '+ logoutToken)
        logout(logoutToken).then(() => {
          // if (process.env.VUE_APP_SSO == 'true') {
          //   let sevice = 'http://' + window.location.host + '/'
          //   let serviceUrl = encodeURIComponent(sevice)
          //   window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
          // }
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },


  }
}

export default user
